package com.demo.config;

import com.demo.mapper.RoleMapper;
import com.demo.pojo.Power;
import com.demo.pojo.Role;
import com.demo.pojo.User;
import com.demo.service.RoleService;
import com.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author chenyuan
 * @date 2020/9/23 20:48
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    //授权

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();
        // 根据身份信息获取当前用户的角色信息、权限信息
        User users = userService.getUserAndRole(principal);
        List<Role> roles = users.getRoles();
        //获取角色信息
        if (!CollectionUtils.isEmpty(roles)){
            //如果集合不为空
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roles.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                // 获取权限信息
                List<Power> powers = roleService.getRoleAndPower(role.getId()).getPowers();
                if (!CollectionUtils.isEmpty(powers)){
                    powers.forEach(power -> {
                        simpleAuthorizationInfo.addStringPermission(power.getName());
                        System.out.println(power);
                    });
                }

                System.out.println(role.getName());
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //打印一个提示
        System.out.println("执行了认证方法");

        //通过参数获取登录的控制器中生成的 令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String principal = token.getUsername();

        // 用户名密码
        User user = userService.getUserByName(principal);
        if (user != null){
            //密码认证， Shiro 自己做，为了避免和密码的接触
            //最后返回一个 AuthenticationInfo 接口的实现类，这里选择 SimpleAuthenticationInfo
            // 四个参数：获取当前用户的认证 ； 密码 ；注册时使用的随机盐 ；当前 Realm 名
            return new SimpleAuthenticationInfo(principal, user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()), this.getName());
        }else {
            // return null 就抛出没有该用户的异常
            return null;
        }


    }
}
